package com.android.djlmapp.application;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.android.djlmapp.http.HttpTools;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.inuker.bluetooth.library.BluetoothContext;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.meiqia.core.MQManager;
import com.meiqia.core.callback.OnInitCallback;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.pddstudio.preferences.encrypted.EncryptedPreferences;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.tinker.entry.DefaultApplicationLike;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;

/**
 * 作者:张鹏
 * 创建时间:16/11/25 下午16:28
 */
public class MyApplication extends DefaultApplicationLike {
    private File cacheDir;
    private static Toast toast;
    private String registrationId = "";
    static MyApplication mInstanse;

    public MyApplication(Application application, int tinkerFlags, boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime, long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime, applicationStartMillisTime, tinkerResultIntent);
    }

    public static MyApplication getInstance() {
        return mInstanse;
    }


    private HttpTools httpTools;

    public HttpTools getHttpTools() {
        return httpTools;
    }

    private EncryptedPreferences encryptedPreferences = null;

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化蓝牙
        BluetoothContext.set(getApplication());

        //初始化加密配置文件
        encryptedPreferences = new EncryptedPreferences.Builder(getApplication()).withEncryptionPassword("DJLM2018FeiHong").build();
        mInstanse = this;
        ForegroundCallbacks init = ForegroundCallbacks.init(getApplication());

        // 初始化网络请求工具类
        httpTools = new HttpTools();

        cacheDir = StorageUtils.getOwnCacheDirectory(getApplication(), "imageloader/Cache");
        ImagerloaderInit();

        //OkGo调用初始化
        okGoInit();
        // 美恰SDK初始化
        initMeiqiaSDK();

        MQManager.setDebugMode(true);
        toast = Toast.makeText(getApplication(), "", Toast.LENGTH_SHORT);

        ZXingLibrary.initDisplayOpinion(getApplication());
        // 极光推送
        setJPushInit();
        // 监听是否在后台
        init.addListener(mListener);
        /**
         * 设置本包为开发设备包
         * true为测试基准包
         */
//        Bugly.setIsDevelopmentDevice(getApplication(),true);
        Bugly.setIsDevelopmentDevice(getApplication(),false);
        // 初始化Tinker  第二个参数为APPID,第三个参数判断当前是否是Debug模式,签名时改为false
        Bugly.init(getApplication(), "53dbfcfce0", false);
    }


    private void initMeiqiaSDK() {
        MQManager.setDebugMode(true);
        // 替换成自己的key
        String meiqiaKey = "e7a6dd64d9e80f95a223f46aafc8198f";
        MQConfig.init(getApplication(), meiqiaKey, new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {
            }

            @Override
            public void onFailure(int code, String message) {
            }
        });

        // 可选
        customMeiqiaSDK();
    }

    private void customMeiqiaSDK() {
        // 配置自定义信息
        MQConfig.ui.titleGravity = MQConfig.ui.MQTitleGravity.LEFT;
        //abc_ic_ab_back_mtrl_am_alpha
        MQConfig.ui.backArrowIconResId = android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material;

    }

    public ForegroundCallbacks.Listener mListener = new ForegroundCallbacks.Listener() {
        @Override
        public void onBecameForeground() {
            Log.e("ForegroundCallbacks项目异常", "------进入前台------");
            MQManager.getInstance(getApplication()).openMeiqiaService();
        }

        @Override
        public void onBecameBackground() {
            Log.e("ForegroundCallbacks项目异常", "------进入后台------");
            MQManager.getInstance(getApplication()).closeMeiqiaService();
        }
    };

    public String getRegistrationId() {
        if(TextUtils.isEmpty(registrationId)){
            UserInfoUtils userInfoUtils = UserInfoUtils.getUserInfoUtilsInstance();
            String pushid = userInfoUtils.getPushId();
            registrationId = pushid;
        }
        return registrationId;
    }

    public void setRegistrationId(String registrationId) {
        if(!TextUtils.isEmpty(registrationId)){
            UserInfoUtils userInfoUtils = UserInfoUtils.getUserInfoUtilsInstance();
            userInfoUtils.setPushId(registrationId);
            this.registrationId = registrationId;
        }
    }

    private void okGoInit() {
        HttpHeaders headers = new HttpHeaders();
        HttpParams params = new HttpParams();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        //添加OkGo默认debug日志
        builder.addInterceptor(loggingInterceptor);

        //超时时间设置，默认60秒
        //全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //使用sp保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
        //使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(getApplication())));
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失

        //https相关设置，以下几种方案根据需要自己设置
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();

        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
        //必须调用初始化
        OkGo.getInstance().init(getApplication())
                //建议设置OkHttpClient，不设置会使用默认的
                .setOkHttpClient(builder.build())
                //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheMode(CacheMode.NO_CACHE)
                //全局统一缓存时间，默认永不过期，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .setRetryCount(3)
                //全局公共头
                .addCommonHeaders(headers)
                //全局公共参数
                .addCommonParams(params);
    }

    private void ImagerloaderInit() {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplication())
                //即保存的每个缓存文件的最大长宽,默认等于你的屏幕尺寸，设备屏幕宽高
                .memoryCacheExtraOptions(480, 800)
                .threadPoolSize(3)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)//线程优先级,普通-2
                //设置内存缓存不允许缓存一张图片的多个尺寸，默认允许。
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) //你可以通过自己的内存缓存实现
                //memoryCacheSize 为 0，则设置该内存缓存的最大字节数为 App 最大可用内存的 1/8。
                // 创建最大的内存缓存百分比，默认为 13%
                .memoryCacheSizePercentage(10)
                .memoryCacheSize(2 * 1024 * 1024) //内存缓存大小
                .diskCacheSize(50 * 1024 * 1024) //磁盘缓存大小
                // 硬盘缓存文件名生成器，默认为哈希文件名生成器 new HashCodeFileNameGenerator()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密
                //集合类型的队列处理任务加载和显示图像,LIFO为后进先出,默认为：FIFO 先进先出
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCacheFileCount(100) //缓存的文件数量
                .diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
                .imageDownloader(new BaseImageDownloader(getApplication(), 5 * 1000, 30 * 1000)) //网络连接时间 (5 s), readTimeout(30 s)超时时间
                //图片显示的配置项。比如加载前、加载中、加载失败应该显示的占位图片，图片是否需要在磁盘缓存，是否需要在内存缓存等。
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .writeDebugLogs() // 显示调试的log信息
                .build();//开始构建
        ImageLoader.getInstance().init(config);
    }


    /**
     * @param str 吐司的内容
     */
    public static void showToast(String str) {
        if (!TextUtils.isEmpty(str) && str != null) {
            toast.setText(str);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        MultiDex.install(getApplication());
        // 安装Tinker
        Beta.installTinker(this);
    }

    public EncryptedPreferences getEncryptedPreferences() {
        return encryptedPreferences;
    }

    public void setJPushInit() {
        try {
            JPushInterface.setDebugMode(true);
            JPushInterface.init(getApplication());
            registrationId = JPushInterface.getRegistrationID(getApplication());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

}